﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Win32;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using XH.SmartParking.Base;
using XH.SmartParking.IService;
using XH.SmartParking.Entities;
using XH.SmartParking.Models;
using XH.SmartParking.Service;

namespace XH.SmartParking.ViewModels
{
    public class MainViewModel : BindableBase
    {
        List<Entities.SysMenu> origMenus;

        public UserModel CurrentUser { get; set; } = new UserModel();
        public DelegateCommand ModifyPasswordCommand { get; set; }
        public DelegateCommand SwitchCommand { get; set; }
        public DelegateCommand<string> SetAvatarCommand { get; set; }

        public DelegateCommand ShowMonitorCommand { get; set; }

        public bool IsDropdownAvatar { get; set; }

        IDialogService _dialogService;
        IRegionManager _regionManager;
        IMenuService _menuService;
        IUserService _userService;
        IRoleService _roleService;
        public MainViewModel(IDialogService dialogService,
            IRegionManager regionManager,
            IMenuService menuService,
            IUserService userService,
            IRoleService roleService,
            IEventAggregator eventAggregator)
        {
            _regionManager = regionManager;
            _menuService = menuService;
            _dialogService = dialogService;
            _userService = userService;
            _roleService = roleService;

            // 打开登录窗口
            dialogService.ShowDialog("LoginView",
                result =>
                {
                    if (result.Result != ButtonResult.OK)
                    {
                        Environment.Exit(0);
                    }
                    else
                    {
                        // 记录当前登录用户信息
                        var su = result.Parameters.GetValue<SysUser>("user");
                        CurrentUser.UserId = su.UserId;
                        CurrentUser.UserName = su.UserName;
                        CurrentUser.RealName = su.RealName;
                        CurrentUser.Password = su.Password;
                        CurrentUser.UserIcon = "pack://siteoforigin:,,,/Avatarts/" + su.UserIcon;
                        CurrentUser.Gender = su.Gender;
                        CurrentUser.Address = su.Address;
                        CurrentUser.Age = su.Age;
                        CurrentUser.Status = su.Status;
                        CurrentUser.Phone = su.Phone;
                        CurrentUser.Roles = su.Roles.Select(r => new RoleModel { RoleId = r.RoleId }).ToList();
                    }
                });






            // 当前窗口要做的事

            OpenViewCommand = new DelegateCommand<MenuItemModel>(DoOpenView);

            ModifyPasswordCommand = new DelegateCommand(DoModifyPassword);

            SwitchCommand = new DelegateCommand(DoSwitch);

            SetAvatarCommand = new DelegateCommand<string>(DoSetAvatar);

            ShowMonitorCommand = new DelegateCommand(DoShowMonitor);

            eventAggregator.GetEvent<RefreshMenuEvent>()
                .Subscribe(() =>
                {
                    LoadMenus();
                });
            // 加载菜单
            LoadMenus();
        }

        private void LoadMenus()
        {
            Menus.Clear();
            // 获取所有菜单
            // 确认当前用户有哪些权限  CurrentUser.Roles  RoleId
            // 根据RoleId  获取角色下的所有MenuID
            var rs = _roleService.Set<SysRole>()
                .Include(r => r.Menus)
                .Where(r => CurrentUser.Roles.Select(cr => cr.RoleId).Contains(r.RoleId)).ToList();

            List<int> mis = new List<int>();
            rs.ForEach(r => mis.AddRange(r.Menus.Select(rm => rm.MenuId)));
            // 根据MenuId  获取所有的菜单信息
            origMenus = _menuService.Query<SysMenu>(m => mis.Contains(m.MenuId)).ToList();

            //origMenus = _menuService.GetMenuList().ToList();
            // 树状填充
            //FillMenus(Menus, 0);
            MenuHelper.FillMenus(Menus, null, origMenus, false);
        }

        #region 菜单相关功能
        public DelegateCommand<MenuItemModel> OpenViewCommand { get; set; }


        private ObservableCollection<MenuItemModel> _menus =
            new ObservableCollection<MenuItemModel>();

        public ObservableCollection<MenuItemModel> Menus
        {
            get { return _menus; }
            set { SetProperty(ref _menus, value); }
        }


        private void DoOpenView(MenuItemModel model)
        {
            // 需要判断：双击的是父节点的时候，关闭或者打开；双击的是子节点，打开对应的页面
            if (model.Children != null && model.Children.Count > 0)
            {
                model.IsExpanded = !model.IsExpanded;
            }
            else if (!string.IsNullOrEmpty(model.TargetView))
            {
                NavigationParameters nps = new NavigationParameters();
                nps.Add("user", CurrentUser);
                _regionManager.RequestNavigate("MainRegion", model.TargetView, nps);
            }

        }
        #endregion


        public void DoModifyPassword()
        {
            DialogParameters param = new DialogParameters();
            param.Add("uid", CurrentUser.UserId);
            param.Add("pwd", CurrentUser.Password);
            _dialogService.ShowDialog(
                "ModifyPasswordView",
                param,
                result =>
                {
                    // 密码修改完成后的回调逻辑？
                    // 如果修改完成
                    if (result.Result == ButtonResult.OK)
                    {
                        // 重启应用，重新登录
                        // 提示一下   是否立即重启，允许用户选择，不然直接重启会有些唐突
                        // 自己完善

                        //
                        //Process.Start("XH.SmartParking.exe");
                        //System.Environment.Exit(0);
                        DoSwitch();
                    }
                });
        }

        public void DoSwitch()
        {
            // 切换用户
            // 
            Process.Start("XH.SmartParking.exe");
            Environment.Exit(0);
        }

        private void DoSetAvatar(string avatar)
        {
            try
            {
                if (string.IsNullOrEmpty(avatar))
                {
                    // 打开选择文件窗口
                    OpenFileDialog dialog = new OpenFileDialog();
                    dialog.Filter = "*.jpg,*.png,*.jpeg|*.jpg;*.png;*.jpeg";
                    dialog.CheckFileExists = true;
                    if (dialog.ShowDialog() == true)
                    {
                        // 开发头像选择功能的时候，可能还需要做图像的裁切

                        // XXXXX.jpg
                        avatar = dialog.SafeFileName;//文件名称，不是路径
                        // 可能出现：两次选择了不同目录下的两个图像文件，这两个文件名称一致
                        // 但是在判断的时候，以是名称来时行判断的，导致后一次图像无法替代
                        // 如果需要解决：可以使用用户ID进行图像文件的重命名（复制的时候，以用用户ID作为图像文件的名称）
                        //　　　　 注意：二次修改的时候需要覆盖操作（涉及图像文件的占用问题）
                        // 如果需要解决文件占用问题的话，需要将图像进行内在读取，然后转ImageSource对象，提供给页面显示

                        // 复制到当前目录下
                        string target_path =
                             Path.Combine(Environment.CurrentDirectory, "Avatarts", avatar);
                        if (!File.Exists(target_path))
                        {
                            File.Copy(dialog.FileName, target_path);
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                // avatar:文件名称

                var user = _userService.Find<SysUser>(CurrentUser.UserId);
                user.UserIcon = avatar;
                _userService.Update(user);

                CurrentUser.UserIcon = "pack://siteoforigin:,,,/Avatarts/" + avatar;

                IsDropdownAvatar = false;
                RaisePropertyChanged(nameof(IsDropdownAvatar));
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        private void DoShowMonitor()
        {
            // MonitorView加载出来
            NavigationParameters nps = new NavigationParameters();
            nps.Add("user", CurrentUser);
            _regionManager.RequestNavigate("MonitorRegion", "MonitorView", nps);


            var region = _regionManager.Regions["MonitorRegion"];
            if (region == null) return;

            var view = region.Views.FirstOrDefault();
            VisualStateManager.GoToElementState((FrameworkElement)view, "ShowState", true);
        }
    }
}
